package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.adapter.LooperAdapter;
import com.gongpingjialoan.adapter.car.CarlistSelectFilterAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AppData;
import com.gongpingjialoan.bean.BannerBean;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.SelectBean;
import com.gongpingjialoan.bean.VIPEb;
import com.gongpingjialoan.bean.VipBuycarBean;
import com.gongpingjialoan.bean.car.BrandBean;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.SharedPreferencesUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.view.MaterialOneSlider;
import com.gongpingjialoan.view.RLScrollView;
import com.gongpingjialoan.widget.AddBrandView;
import com.gongpingjialoan.widget.autoviewpagers.ColorPointHintView;
import com.gongpingjialoan.widget.autoviewpagers.RollPagerView;
import com.gongpingjialoan.wxapi.WXPayEntryActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Administrator on 2016/6/23.
 */
public class IntentFragment extends AnimationFragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    public BuyCarVipActivity mBuyCarVipActivity;

    private View view, otherMain;

    private static final int REQUEST_BRAND = 0x1010;

    private static final int REQUEST_CITY = 0x1011;

    private TextView cityTextView;

    private AddBrandView mAddBrandView;

    public MaterialOneSlider mMaterialOneSlider;

    private RLScrollView mScrollView;

    private int price;

    private NetDataJson mNetDataJson;

    private String city;

    //购车时间    (多选)
    private String[] show_time = {"1~2周内", "1个月内", "2个月内", "半年内", "先看看"};
    private String[] need_time = {"one_or_two_weeks", "one_month", "two_months", "six_months", "not_set"};

    //颜色   (多选)
    private String[] show_color = {"黑", "白", "灰", "红", "银", "蓝", "金", "棕", "颜色不限"};
    private String[] need_color = {"黑", "白", "灰", "红", "银", "蓝", "金", "棕", ""};

    //车龄   (多选)
    private String[] show_age = {"1年内", "2年内", "3年内", "4年内", "5年内", "车龄不限"};
    private String[] need_age = {"1", "2", "3", "4", "5", "车龄不限"};

    //里程   (多选)
    private String[] show_mile = {"1-5万km", "5-10万km", "10万km以上"};
    private String[] need_mile = {"1-5", "5-10", "10-"};

    private GridView timeGridView, colorGridView, ageGridView, mileGridView;

    private CarlistSelectFilterAdapter adapter_time, adapter_color, adapter_age, adapter_mile;

    private List<SelectBean> list_time, list_color, list_age, list_mile;

    private String str_time = "", str_color = "", str_age = "", str_mile = "";

    private Handler mHandler = new Handler();

    private RollPagerView mRollPagerView;

    private LooperAdapter mLooperAdapter;

    private LinearLayout rollLinearLayout;

    private Button sure_button;

    private AppCompatEditText mAppCompatEditText;

    private EditText edit_other;

    private boolean isPhoneNumRight = false;

    private View loginLinearLayout;

    private VipBuycarBean mVipBuycarBean;

    final int LOGIN = 1001;

    UserManager mUserManager;
    //为false代表从贷款那边过来
    boolean show_time_and_note;

    TextView loan_desT;

    CheckBox fenqi_checkC;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        action = "vipBuy";
        isScrollPage = true;
        view = inflater.inflate(R.layout.intent_layout, container, false);
        mBuyCarVipActivity = (BuyCarVipActivity) getActivity();
        initView();
        initBanner();
        return view;
    }


    public void initBanner() {
        BannerBean bannerBean = GPJApplication.getInstance().mBannerBean;
        if (bannerBean != null && "success".equals(bannerBean.getStatus())) {
            List<BannerBean.DataEntity.EvalEntity> dataEntities = bannerBean.getData().getVipbuy();
            if (dataEntities != null && dataEntities.size() > 0) {
                Glide.with(mBuyCarVipActivity).load(dataEntities.get(0).getImg()).into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        int width = getResources().getDisplayMetrics().widthPixels;
                        int height = resource.getIntrinsicHeight() * width / resource.getIntrinsicWidth();
                        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
                        rollLinearLayout.addView(mRollPagerView, lp);
                    }
                });
                view.findViewById(R.id.vip_zu).setVisibility(View.GONE);
                mRollPagerView.setVisibility(View.VISIBLE);
                mLooperAdapter = new LooperAdapter(mRollPagerView, dataEntities, getActivity(), getFragmentManager(), false);
                mRollPagerView.setAdapter(mLooperAdapter);
            }
        }
    }


    private void initView() {
        loan_desT = (TextView) view.findViewById(R.id.loan_des);
        fenqi_checkC = (CheckBox) view.findViewById(R.id.fenqi_check);
        show_time_and_note = getActivity().getIntent().getBooleanExtra("noshow_time_and_note", true);
//        view.findViewById(R.id.other_layout).setVisibility(show_time_and_note ? View.VISIBLE : View.GONE);
        view.findViewById(R.id.time_layout).setVisibility(View.GONE);


        loginLinearLayout = view.findViewById(R.id.loginlayout);
        mAppCompatEditText = (AppCompatEditText) view.findViewById(R.id.phone);
        if (GPJApplication.getInstance().isLogin()) {
            loginLinearLayout.setVisibility(View.GONE);
        } else {
            String phone = (String) SharedPreferencesUtil.get(mBuyCarVipActivity, "vip_phone", "");
            if (!TextUtils.isEmpty(phone)) {
                isPhoneNumRight = true;
                mAppCompatEditText.setText(phone);
            }
        }
        edit_other = (EditText) view.findViewById(R.id.edit_other);
        sure_button = (Button) view.findViewById(R.id.sure_button);

        rollLinearLayout = (LinearLayout) view.findViewById(R.id.rollmain);
        mRollPagerView = new RollPagerView(getActivity());
        mRollPagerView.setHintView(new ColorPointHintView(getActivity(), Color.WHITE, Color.GRAY));
        mRollPagerView.setPlayDelay(3000);
        mRollPagerView.setVisibility(View.GONE);


        mScrollView = (RLScrollView) view.findViewById(R.id.scrollview);
        otherMain = view.findViewById(R.id.other_main);
        mAddBrandView = (AddBrandView) view.findViewById(R.id.add_brand);
        //从贷款那边过来，只允许选择一个车型
        if (!show_time_and_note) {
            mAddBrandView.setMaxCount(1);
        }
        mAddBrandView.setIntentFragment(this);
        sure_button.setOnClickListener(this);
        cityTextView = (TextView) view.findViewById(R.id.city);
        city = ((GPJApplication) getActivity().getApplication()).getCityData().mCurrentCity;
        cityTextView.setText(city);
        mMaterialOneSlider = (MaterialOneSlider) view.findViewById(R.id.slider);
        mMaterialOneSlider.setOnClickListener(this);
        mMaterialOneSlider.setRangeSliderListener(new MaterialOneSlider.RangeOneListener() {
            @Override
            public void onMaxChanged(int newValue) {
            }

            @Override
            public void onMinChanged(int newValue) {
                price = newValue;
                setLoanInfo(price * 10000);
                setSureButton();
            }
        });

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mMaterialOneSlider.isMakeSure = false;
            }
        }, 500);

        cityTextView.setOnClickListener(this);
        timeGridView = (GridView) view.findViewById(R.id.time);
        adapter_time = new CarlistSelectFilterAdapter(mBuyCarVipActivity);
        timeGridView.setOnItemClickListener(this);
        timeGridView.setAdapter(adapter_time);

        colorGridView = (GridView) view.findViewById(R.id.color);
        adapter_color = new CarlistSelectFilterAdapter(mBuyCarVipActivity);
        colorGridView.setOnItemClickListener(this);
        colorGridView.setAdapter(adapter_color);

        ageGridView = (GridView) view.findViewById(R.id.age);
        adapter_age = new CarlistSelectFilterAdapter(mBuyCarVipActivity);
        ageGridView.setOnItemClickListener(this);
        ageGridView.setAdapter(adapter_age);

        mileGridView = (GridView) view.findViewById(R.id.mile);
        adapter_mile = new CarlistSelectFilterAdapter(mBuyCarVipActivity);
        mileGridView.setOnItemClickListener(this);
        mileGridView.setAdapter(adapter_mile);

        mAppCompatEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String phone = mAppCompatEditText.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    isPhoneNumRight = false;
                    setSureButton();
                    return;
                }
                if (phone.length() < 11 || !phone.startsWith("1")) {
                    isPhoneNumRight = false;
                    setSureButton();
                    return;
                }
                isPhoneNumRight = true;
                setSureButton();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        Intent it = getActivity().getIntent();

        //不为空代表从买车查价详情过来的
        if (!TextUtils.isEmpty(it.getStringExtra("price"))) {
            initData(it);
        }

        getSaveData();
        initGridView();

        mUserManager = new UserManager(getActivity());
        mUserManager = mUserManager.LoadUserInfo();
//        if (!show_time_and_note) {
//            view.findViewById(R.id.buy_layout).setVisibility(View.GONE);
//        } else {
//        view.findViewById(R.id.buy_layout).setVisibility(mUserManager.is_vip() ? View.GONE : View.VISIBLE);
//        }


        view.findViewById(R.id.buy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (GPJApplication.getInstance().isLogin()) {
                    Intent it = new Intent(getActivity(), WXPayEntryActivity.class);
                    it.putExtra("action_type", "vip_buy");
                    startActivity(it);
                } else {
                    Intent it = new Intent(getActivity(), LoginActivity.class);
                    startActivityForResult(it, LOGIN);
                }
                StepMonitor.getInstance().addMonitor(new Monitor("click", "vipBuy_vipPay", System.currentTimeMillis(), 1f));
            }
        });


        TextView priceT = (TextView) view.findViewById(R.id.vip_price);
        TextView vip_desT = (TextView) view.findViewById(R.id.vip_des);
        TextView vip_oldpriceT = (TextView) view.findViewById(R.id.vip_oldprice);
        vip_oldpriceT.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        AppData data = GPJApplication.getInstance().mAppData;
        if (data != null) {
            priceT.setText("¥" + (int) (data.getData().getVip_charge_price().getValue() / 100f));
            vip_desT.setText("排除事故车、泡水车、火烧车(已有" + data.getData().getVip_buy_count().getValue() + "人选择)");
        }
    }

    private void initData(Intent it) {


        String brandSlug = it.getStringExtra("brandSlug");
        String brandName = it.getStringExtra("brandName");
        String modelSlug = it.getStringExtra("modelSlug");
        String modelName = it.getStringExtra("modelName");
        String mile = it.getStringExtra("mile");
        initMile(Double.parseDouble(mile));

        BrandBean brandBean = new BrandBean();
        brandBean.brand_slug = brandSlug;
        brandBean.brand = brandName;
        brandBean.model_slug = modelSlug;
        brandBean.model = modelName;
//        brandBean.price = bundle.getString("price");
//        if (TextUtils.isEmpty(brandBean.price)) {
        getModelDetail(brandBean, true);
//        } else {
//            mAddBrandView.addBrand(brandBean);
//            mMaterialOneSlider.minValue = 0;
//            mMaterialOneSlider.reset();
//            mMaterialOneSlider.setMax((int) getMaxPrice() + 5);
//            mMaterialOneSlider.calculateConvertFactor();
//            setSureButton();
//        }


    }

    private void initMile(double mile) {
        if (mile <= 5) {
            str_mile = "1-5";
        } else if (mile > 10) {
            str_mile = "10-";
        } else {
            str_mile = "5-10";
        }

    }

    private void setLoanInfo(int price) {
        if (price != 0) {
            loan_desT.setVisibility(View.VISIBLE);
        } else {
            loan_desT.setVisibility(View.INVISIBLE);
            return;
        }
        BigDecimal p1 = new BigDecimal(Double.toString(price));
        BigDecimal p2 = new BigDecimal(Double.toString(0.3));
        BigDecimal p3 = new BigDecimal(Double.toString(0.0055));
        BigDecimal p4 = new BigDecimal(Double.toString(0.7));
        double first_pay = new BigDecimal(p1.multiply(p2).floatValue() / 10000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
        double loan_price = p1.multiply(p4).doubleValue();
        BigDecimal p5 = new BigDecimal(Double.toString(loan_price));
        int month_pay = new BigDecimal(p5.divide(new BigDecimal(Double.toString(36)), 4, BigDecimal.ROUND_HALF_UP).doubleValue()
                + p5.multiply(p3).doubleValue()).setScale(1, BigDecimal.ROUND_HALF_UP).
                setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        loan_desT.setText("(首付" + first_pay + "万  36期  月供" + month_pay + "元)");
    }

    private void getSaveData() {
        if (mBuyCarVipActivity.vipBuyEntity == null) return;
        price = Integer.parseInt(mBuyCarVipActivity.vipBuyEntity.getPrice());
    }


    private void initGridView() {
        List<String> times = null;
        int size = 0;
        if (!TextUtils.isEmpty(str_time)) {
            times = Arrays.asList(str_time.split(","));
            size = times.size();
        }
        list_time = new ArrayList<SelectBean>();
        for (int i = 0; i < show_time.length; i++) {
            SelectBean bean = new SelectBean(show_time[i], need_time[i], false);
            if (times != null && !times.isEmpty()) {
                for (int j = 0; j < size; j++) {
                    if (need_time[i].equals(times.get(j))) {
                        bean.setCheack(true);
                    }
                }
            }
            list_time.add(bean);
        }


        List<String> colors = null;
        if (!TextUtils.isEmpty(str_color)) {
            colors = Arrays.asList(str_color.split(","));
            size = colors.size();
        }
        list_color = new ArrayList<SelectBean>();
        for (int i = 0; i < show_color.length; i++) {
            SelectBean bean = new SelectBean(show_color[i], need_color[i], false);
            if (colors != null && !colors.isEmpty()) {
                for (int j = 0; j < size; j++) {
                    if (need_color[i].equals(colors.get(j))) {
                        bean.setCheack(true);
                    }
                }
            }
            list_color.add(bean);
        }


        List<String> ages = null;
        if (!TextUtils.isEmpty(str_age)) {
            ages = Arrays.asList(str_age.split(","));
            size = ages.size();
        }
        list_age = new ArrayList<SelectBean>();
        for (int i = 0; i < show_age.length; i++) {
            SelectBean bean = new SelectBean(show_age[i], need_age[i], false);
            if (ages != null && !ages.isEmpty()) {
                for (int j = 0; j < size; j++) {
                    if (need_age[i].equals(ages.get(j))) {
                        bean.setCheack(true);
                    }
                }
            }
            list_age.add(bean);
        }


        List<String> miles = null;
        if (!TextUtils.isEmpty(str_mile)) {
            miles = Arrays.asList(str_mile.split(","));
            size = miles.size();
        }
        list_mile = new ArrayList<SelectBean>();
        for (int i = 0; i < show_mile.length; i++) {
            SelectBean bean = new SelectBean(show_mile[i], need_mile[i], false);
            if (miles != null && !miles.isEmpty()) {
                for (int j = 0; j < size; j++) {
                    if (need_mile[i].equals(miles.get(j))) {
                        bean.setCheack(true);
                    }
                }
            }
            list_mile.add(bean);
        }


        adapter_time.setData(list_time);
        adapter_color.setData(list_color);
        adapter_age.setData(list_age);
        adapter_mile.setData(list_mile);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_BRAND) {
                Bundle bundle = data.getExtras();
                BrandBean brandBean = new BrandBean();
                brandBean.brand_slug = bundle.getString("brandSlug");
                brandBean.brand = bundle.getString("brandName");
                brandBean.model_slug = bundle.getString("modelSlug");
                brandBean.model = bundle.getString("modelName");
                brandBean.price = bundle.getString("price");
                if (TextUtils.isEmpty(brandBean.price)) {
                    getModelDetail(brandBean, false);
                } else {
                    mAddBrandView.addBrand(brandBean);
                    mMaterialOneSlider.minValue = 0;
                    mMaterialOneSlider.reset();
                    mMaterialOneSlider.setMax((int) getMaxPrice() + 5);
                    mMaterialOneSlider.calculateConvertFactor();
                    setSureButton();
                }


            } else if (requestCode == REQUEST_CITY) {
                Bundle b = data.getExtras();
                city = b.getString("city");
                if (!TextUtils.isEmpty(city)) {
                    cityTextView.setText(city);
                }
            } else if (requestCode == LOGIN) {
                loginLinearLayout.setVisibility(View.GONE);
                UserManager mUserManager = new UserManager(getActivity());
                mUserManager = mUserManager.LoadUserInfo();
                if (mUserManager.is_vip()) {
//                    view.findViewById(R.id.buy_layout).setVisibility(View.GONE);
                    setSureButton();
                } else {
                    Intent it = new Intent(getActivity(), WXPayEntryActivity.class);
                    it.putExtra("action_type", "vip_buy");
                    startActivity(it);
                }
            }
        }
    }


    private void getModelDetail(final BrandBean brandBean, final boolean needSelect) {
        mBuyCarVipActivity.showProgressDialog("加载中...");
        if (mNetDataJson == null) {
            mNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    brandBean.price = "0";
                    mAddBrandView.addBrand(brandBean);
                    mMaterialOneSlider.minValue = 0;
                    mMaterialOneSlider.reset();
                    mMaterialOneSlider.setMax(1000);

                    mMaterialOneSlider.calculateConvertFactor();
                    mBuyCarVipActivity.hidenProgressDialog();
                    setSureButton();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    brandBean.price = getMaxPriceFromJson(json);
                    mAddBrandView.addBrand(brandBean);
                    mMaterialOneSlider.minValue = 0;
                    mMaterialOneSlider.reset();
                    mMaterialOneSlider.setMax((int) getMaxPrice() + 5);
                    mMaterialOneSlider.calculateConvertFactor();
                    if (needSelect) {
//                        mMaterialOneSlider.minValue = 10;
                        String price = getActivity().getIntent().getStringExtra("price");

//
//                            public void run() { new Handler().postDelayed(new Runnable() {
//                            @Override
                        mMaterialOneSlider.isMakeSure = false;
                        mMaterialOneSlider.setSelectedMin((int) Double.parseDouble(price));
//                            }
//                        }, 500);
                    }

                    mBuyCarVipActivity.hidenProgressDialog();
                    setSureButton();
                }
            });
        }
        mNetDataJson.setUrl(API.modelDetail);
        mNetDataJson.addParam("brand", brandBean.brand_slug);
        mNetDataJson.addParam("model", brandBean.model_slug);
        mNetDataJson.request("get");
    }

    private String getMaxPriceFromJson(JSONObject json) {
        double maxprice = 0;
        try {
            JSONArray detail = json.getJSONArray("detail_model");
            int size = detail.length();
            for (int i = 0; i < size; i++) {
                JSONObject jo = detail.getJSONObject(i);
                double max = Double.parseDouble(jo.getString("price_bn"));
                if (max >= maxprice) {
                    maxprice = max;
                }
            }
        } catch (JSONException e) {
        }
        return (int) maxprice + "";
    }


    private float getMaxPrice() {
        List<BrandBean> brandBeans = mAddBrandView.getBrandBeans();
        BrandBean max = Collections.max(brandBeans, new BrandComparator());
        return Float.parseFloat(max.price);
    }

    class BrandComparator implements Comparator<BrandBean> {
        public int compare(BrandBean o1, BrandBean o2) {
            float f1 = Float.parseFloat(o1.price);
            float f2 = Float.parseFloat(o2.price);
            return (f1 < f2 ? -1 : (f1 == f2 ? 0 : 1));
        }
    }

    @Override
    public void onClick(View v) {
        if (v == cityTextView) {
            Intent intent = new Intent();
            intent.putExtra("needProvince", false);
            intent.setClass(getActivity(), CityActivity.class);
            startActivityForResult(intent, REQUEST_CITY);
        } else if (v == sure_button) {
            String phone;
            if (!GPJApplication.getInstance().isLogin()) {
                phone = mAppCompatEditText.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(mBuyCarVipActivity, "请输入手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (phone.length() < 11 || !phone.startsWith("1")) {
                    Toast.makeText(mBuyCarVipActivity, "手机号输出有误,请重新输入", Toast.LENGTH_SHORT).show();
                    return;
                }
                SharedPreferencesUtil.put(mBuyCarVipActivity, "vip_phone", mAppCompatEditText.getText().toString());
            } else {
                UserManager mUserManager = new UserManager(mBuyCarVipActivity);
                mUserManager = mUserManager.LoadUserInfo();
                phone = mUserManager.getPhone();
            }
            mVipBuycarBean = new VipBuycarBean();
            mVipBuycarBean.setUseloan(fenqi_checkC.isChecked() ? "true" : "false");
            mVipBuycarBean.setPrice(price + "");
            mVipBuycarBean.setBrand_models(mAddBrandView.getBrandModels());
            mVipBuycarBean.setTimes(str_time);
            mVipBuycarBean.setColors(str_color);
            mVipBuycarBean.setAge(str_age);
            mVipBuycarBean.setMile(str_mile);
            mVipBuycarBean.setOthers(edit_other.getText().toString());
            mVipBuycarBean.setPhone(phone);
            mVipBuycarBean.setCity(city);
            mVipBuycarBean.setType("specific");
            mVipBuycarBean.setBrand_models_zh(mAddBrandView.getBrandModelsZH());

            String from = getActivity().getIntent().getStringExtra("from");
//            if (TextUtils.isEmpty(from)) {
            //不是从贷款过来的，则跳转
//            if (show_time_and_note) {

            Intent intent = new Intent(mBuyCarVipActivity, VipRecomendCarActivity.class);
            intent.putExtra("mVipBuycarBean", mVipBuycarBean);
            startActivity(intent);
//            } else {
                EventBus.getDefault().post(mVipBuycarBean);
//            }

      /*      } else {
                startActivity(new Intent(getActivity(), SysRecomendCarActivity.class));
            }*/


            StepMonitor.getInstance().addMonitor(new Monitor("click", "vipBuy_submit", System.currentTimeMillis(), 1f));
            mBuyCarVipActivity.finish();
            mUserManager.setBuy_car_recommend_flag(true);
            mUserManager.SaveUserInfo(mUserManager);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent == timeGridView) {
            if (list_time.get(position).isCheack()) {
                resetRadio(list_time);
                str_time = "";
            } else {
                resetRadio(list_time);
                list_time.get(position).setCheack(true);
                str_time = list_time.get(position).getNeed_name();
            }
            adapter_time.setData(list_time);

        } else if (parent == colorGridView) {
            //颜色多选
            str_color = resetChecked(list_color, position);
            adapter_color.setData(list_color);
        } else if (parent == ageGridView) {
            if (list_age.get(position).isCheack()) {
                resetRadio(list_age);
                str_age = "";
            } else {
                resetRadio(list_age);
                list_age.get(position).setCheack(true);
                str_age = list_age.get(position).getNeed_name();
            }
            adapter_age.setData(list_age);
            setSureButton();
        } else if (parent == mileGridView) {
            if (list_mile.get(position).isCheack()) {
                resetRadio(list_mile);
                str_mile = "";
            } else {
                resetRadio(list_mile);
                list_mile.get(position).setCheack(true);
                str_mile = list_mile.get(position).getNeed_name();
            }
            adapter_mile.setData(list_mile);
            setSureButton();
        }
    }

    //重置多选
    private String resetChecked(List<SelectBean> list, int position) {
        SelectBean sb = list.get(position);
        boolean ischeck = sb.isCheack();

        if (position != list.size() - 1) {       //当前选中item不为最后一个
            sb.setCheack(!ischeck);
            list.get(list.size() - 1).setCheack(false);     //最后一个item为false
        } else {      //选择最后一个item
            //最后item为true其他为false
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setCheack(false);
            }
            sb.setCheack(true);
        }
        List<String> checkedName = new ArrayList<String>();       //将为true的字段保存在当前集合
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isCheack()) {
                checkedName.add(list.get(i).getNeed_name());
            }
        }
        String str_name = setcomposing(checkedName);
        return str_name;
    }

    //拼接字符串
    private String setcomposing(List<String> checkedName) {
        String names = "";
        for (int i = 0; i < checkedName.size(); i++) {
            if (i == checkedName.size() - 1) {
                names += checkedName.get(i);
            } else {
                names += checkedName.get(i) + ",";
            }
        }
        return names;
    }

    //重置单选 (设置为false)
    private void resetRadio(List<SelectBean> list) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setCheack(false);
        }
    }


    //判断确认按钮是否可点
    public void setSureButton() {
        if (show_time_and_note) {
            mUserManager = mUserManager.LoadUserInfo();
            if (!TextUtils.isEmpty(str_age) && !TextUtils.isEmpty(str_mile) && price > 0 && mAddBrandView.isHaveBrandModels()) {
                if (loginLinearLayout.getVisibility() == View.VISIBLE) {
                    if (isPhoneNumRight) {
                        sure_button.setBackgroundResource(R.drawable.button_big_bg);
                        sure_button.setEnabled(true);
                        return;
                    } else {
                        sure_button.setBackgroundResource(R.drawable.button_no_click);
                        sure_button.setEnabled(false);
                        return;
                    }
                }
                sure_button.setBackgroundResource(R.drawable.button_big_bg);
                sure_button.setEnabled(true);
            } else {
                sure_button.setBackgroundResource(R.drawable.button_no_click);
                sure_button.setEnabled(false);
            }
        } else {
            if (!TextUtils.isEmpty(str_age) && !TextUtils.isEmpty(str_mile) && price > 0 && mAddBrandView.isHaveBrandModels()) {
                if (loginLinearLayout.getVisibility() == View.VISIBLE) {
                    if (isPhoneNumRight) {
                        sure_button.setBackgroundResource(R.drawable.button_big_bg);
                        sure_button.setEnabled(true);
                        return;
                    } else {
                        sure_button.setBackgroundResource(R.drawable.button_no_click);
                        sure_button.setEnabled(false);
                        return;
                    }
                }
                sure_button.setBackgroundResource(R.drawable.button_big_bg);
                sure_button.setEnabled(true);
            } else {
                sure_button.setBackgroundResource(R.drawable.button_no_click);
                sure_button.setEnabled(false);
            }
        }

    }

    @Subscribe
    public void onEventMainThread(VIPEb VIPEb) {
//        view.findViewById(R.id.buy_layout).setVisibility(View.GONE);
        setSureButton();
    }


}
